<?php

require_once dirname(__FILE__) . '/../protected/extensions/PHPMailer/class.phpmailer.php';

function pr($arr, $die = true) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

function dump($arr, $die = true) {
    echo "<pre>";
    var_dump($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

function read($var) {
    if (isset($var)) {
        $returnVar = $var;
    } else {
        $returnVar = NULL;
    }
    return $var;
}

function writeToFile($arr) {
    $str = "<pre>";
    $str.=print_r($arr, true);
    $str.="</pre>";

    $fp = fopen('file.txt', 'a');
    fwrite($fp, $str);
    fclose($fp);
}

function printMsg($msg) {
    echo $msg . "\n";
}

function guid() {

    if (function_exists('com_create_guid')) {
        $guid = com_create_guid();
        $guid = preg_replace("/[^A-Za-z0-9]/", "", $guid);
        return $guid;
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $guid = substr($charid, 0, 8)
                . substr($charid, 8, 4)
                . substr($charid, 12, 4)
                . substr($charid, 16, 4)
                . substr($charid, 20, 12);
        return $guid;
    }
}

function createThumb($path, $width, $height, $resize = true) {
    Yii::import("ext.phpthumb.EasyPhpThumb");
    ini_set('upload_max_filesize', '10M');
    ini_set('max_execution_time', '1800');

    $thumbs = new EasyPhpThumb();
    $thumbs->init();

    $thumbs->setThumbsDirectory(config::getUploadDir());
    if ($resize) {
        $thumbs->load($path)
                ->resize($width, $height);
        return $thumbs->save();
    } else {
        $thumbs->load($path);
        return $thumbs->save();
    }
}

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

function changePassword($obj, $post) {
    if (isset($post)) {
        $obj->setAttribute('password', md5($post));
        $obj->save(false); // save the change to database
    }
}

function populateEmailTemplate($msgTpl, array $params = NULL) {

    if ($msgTpl != '') {
        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
    }

    $body = '';
    if (file_exists($msgTpl)) {
        $body = file_get_contents($msgTpl);
        if (!empty($params)) {
            foreach ($params as $k => $v)
                $body = str_replace($k, $v, $body);
        }
    }
    return $body;
}

function anotherEmailSend($to, $subject, $body) {

    try {
        /*
          remove when debug finish

          $mail = new PHPMailer(true);
          $mail->IsSMTP();
          $mail->Host = EMAIL_HOST;
          $mail->SMTPAuth = EMAIL_SMTP_AUTH;
          $mail->Username = EMAIL_USER_NAME;
          $mail->Password = EMAIL_PASSWORD;
          $mail->SetFrom(EMAIL_FROM, EMAIL_FROM_NAME);
          $mail->Subject = $subject;
          $mail->MsgHTML($body);
          $mail->IsHTML(true); // send as HTML
          $mail->AddAddress($to);
          $mail->Send();

         */
        /////////////////////////////////////////////////////
        $mail = new PHPMailer(true);

        $mail->IsSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';  // Specify main and backup server
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'raksrivastava@gmail.com';                            // SMTP username
        $mail->Password = '';                           // SMTP password
        $mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

        $mail->From = 'raksrivastava@gmail.com';
        $mail->FromName = 'Rakesh';
        $mail->AddAddress($to); // Add a recipient
        // $mail->AddReplyTo('raksrivastava@gmail.com', 'rakesh');


        $mail->WordWrap = 50;                                 // Set word wrap to 50 characters

        $mail->IsHTML(true);                                  // Set email format to HTML

        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AltBody = $body;

        if (!$mail->Send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            exit;
        }
    } catch (Exception $e) {
        
    }
}

function forgatePasswordEmail($email, $user, $activationLink, $subject, $msgTpl) {
    try {

        $mail = new PHPMailer(true);

        $mail->IsSMTP();
        $mail->Host = EMAIL_HOST;
        $mail->SMTPAuth = EMAIL_SMTP_AUTH;
        $mail->Username = EMAIL_USER_NAME;
        $mail->Password = EMAIL_PASSWORD;
        $mail->SetFrom(EMAIL_FROM, EMAIL_FROM);
        $mail->Subject = $subject;
        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
        // $body = $activationKey;
        $body = '';
        if (file_exists($msgTpl)) {
            $body = file_get_contents($msgTpl);
            $body = str_replace("ACTIVATIONLINK", $activationLink, $body);
        }

        $mail->MsgHTML($body);
        $mail->IsHTML(true); // send as HTML
        $mail->AddAddress($email);
        $mail->Send();
    } catch (Exception $e) {
        
    }
}

function dateTime($date, $dateFormate = 'm-d-Y', $isTime = true, $isAmPm = true, $_12HoursClock = false) {

    $time = "";
    if ($isTime) {
        if ($_12HoursClock) {
            $time = " h:i:s";
        } else {
            $time = " H:i:s";
        }

        if ($isAmPm) {
            $time .= " a";
        }
    }

    $dateFormate = $dateFormate . $time;

    $date = strtotime(str_replace('-', '/', $date));

    if (!empty($date)) {
        return $date = date($dateFormate, $date);
    }

    return NULL;
}

function getReviewRating($id, $is_active = FALSE) {
    $command = Yii::app()->db->createCommand();
    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_admin_approved=:is_admin_approved';
        $conditions = array(':id' => $id, ':is_admin_approved' => 1);
    }
    $sql = 'SELECT rating FROM `review` WHERE id=:id ' . $subSql;
    $rating = $command->setText($sql)
            ->queryScalar($conditions);
    return $rating = calculateRating($rating);
}

function getRating($id, $is_active = FALSE) {
    $command = Yii::app()->db->createCommand();

    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_active=:is_active';
        $conditions = array(':id' => $id, ':is_active' => 1);
    }

    $rating = $command->setText('SELECT `rating_sum` / `rating_count` AS rating FROM `restaurant` WHERE id=:id ' . $subSql)
            ->queryScalar($conditions);

    return $rating = calculateRating($rating);
}

function calculateRating($rating) {
    if ($rating != null) {
        if ($rating >= MAX_RATING) {
            $rating = 5;
        } elseif ($rating <= MIN_RATING) {
            $rating = 0;
        }
        $constent = (int) $rating;
        $remainder = $rating - $constent;
        if ($remainder != 0) {
            if ($remainder < RATING_MIN_LIMIT) {
                $rem = 0.00;
            } elseif ($remainder >= RATING_MAX_LIMIT) {
                $rem = 1.00;
            } else {

                $rem = 0.5;
            }
            $rating = $constent + $rem;
        }

        return number_format($rating, 2, '.', '');
    }
}

function showRating($rating) {

    $string = '';
    $count = (int) $rating;
    $rem = $rating - $count;
    for ($i = 0; $i < MAX_RATING; $i++) {
        if ($i < $count) {
            $img = 'full.png';
        } elseif ($rem != 0) {
            $img = 'half.png';
            $rem = 0;
        } else {
            $img = 'blank.png';
        }

        $string.='<img src="' . Yii::app()->getBaseUrl() . '/images/' . $img . '">';
    }

    return $string;
}

function getExpireTime() {
    //    $increase_time = (int) X_AUTHKEY_INCREASE_EXPIRE_TIME;
    //    $calculate_time =(int) 60 * $increase_time;
    //    $expires_on = time() + $calculate_time;
    $expires_on = strtotime('1-1-2038');
    return $expires_on;
}

function updateExexpireTime($auth_key) {
    $auth = getAuthKeyObj($auth_key);
    if ($auth) {
        $auth_key = $auth->getAttribute('auth_key');
        $expires_on = getExpireTime();
        $auth->setAttribute('expires_on', $expires_on);
        $auth->update();
    }
}

function getAuthKeyObj($auth_key) {
    $expires_on = time();
    $auth_key_obj = AuthKey::model()->find('auth_key=:auth_key AND expires_on >=:expires_on', array(':auth_key' => $auth_key, ':expires_on' => $expires_on));
    return $auth_key_obj;
}

function getLatLongByAddressBYPhp($address) {
    $latitude = '';
    $longitude = '';
//    // $address = $address; // Google HQ
//
//    $prepAddr = str_replace(' ', '+', $address);
//
//
//    $geocode = @file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');
//  
//    $output = json_decode($geocode);
//
//    if (!empty($output)) {
//        if(is_array($output->results) && !empty($output->results)){
//        $latitude = $output->results[0]->geometry->location->lat;
//
//        $longitude = $output->results[0]->geometry->location->lng;
//    }
//    }
// 
//    $latLon = array('lat' => $latitude, 'lon' => $longitude);
//
//    return $latLon;
// retrieve the latitude & longitude from the address
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = json_decode(curl_exec($ch), true);
    if ($response['status'] != 'OK') {
        //echo 'An error has occured: ' . print_r($response);
    } else {
        $geometry = $response['results'][0]['geometry'];
        $latitude = $geometry['location']['lat'];
        $longitude = $geometry['location']['lng'];
    }
    $latLon = array('lat' => $latitude, 'lon' => $longitude);

    return $latLon;
}

function getLatLongByAddress($address) {
    $delay = 0;
    $lat = '';
    $lng = '';
    $base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;

    $request_url = $base_url . "&q=" . urlencode($address);

    $csv = file_get_contents($request_url) or die("url not loading");
    $csvSplit = explode(",", $csv);
    $status = $csvSplit[0];

    if (strcmp($status, "200") == 0) {
        // successful geocode
        $geocode_pending = false;
        $lat = $csvSplit[2];
        $lng = $csvSplit[3];
    } else if (strcmp($status, "620") == 0) {
        // sent geocodes too fast
        $delay += 100000;
    } else {
        // failure to geocode
        $geocode_pending = false;
        "Address " . $address . " failed to geocoded. ";
        "Received status " . $status . "
		\n";
        usleep($delay);
    }

    return array('lat' => $lat, 'long' => $lng);
}

function yiiUserLogOut() {
    //We logout for last session value
    Yii::app()->user->logout();
    Yii::app()->user->clearStates();
    $session = new CHttpSession;
    $session->destroy();
}

function calculateDistance($in_lat, $in_long) {
    /*
     *   Haversine formula:
      a = sin�(?lat/2) + cos(lat1).cos(lat2).sin�(?long/2)
      c = 2.atan2(va, v(1-a))
      d = R.c
     * From http://www.movable-type.co.uk/scripts/latlong.html
     */


    $lat1 = $in_lat;
    $lon1 = $in_long;
    $lat2 = $this->latitude;
    $lon2 = $this->longitude;
    $R = EARTH_RADIUS;

    $dLat = $lat2 - $lat1;
    $dLat = deg2rad($dLat);
    $dLon = $lon2 - $lon1;
    $dLon = deg2rad($dLon);

    $lat1 = deg2rad($lat1);
    $lat2 = deg2rad($lat2);
    $a = sin($dLat / 2) * sin($dLat / 2) + sin($dLon / 2) * sin($dLon / 2) * cos($lat1) * cos($lat2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $R * $c;
    return $distance;
}

function getOffSetForPaging($pageCount, $pageSize) {
    if (!empty($pageCount) && !empty($pageSize)) {
        $start = ($pageCount - 1) * $pageSize;
        $end = ($pageCount * $pageSize) - 1;
        return array('start' => $start, 'end' => $end);
    }
}

function GetDays($sStartDate, $sEndDate, $startDays) {
    $years = date("Y", strtotime($sStartDate));
    $months = date("m", strtotime($sStartDate));
    $dates = date("d", strtotime($sStartDate));
    //echo $dates;
    if ($startDays > $dates) {
        $sStartDate = $years . '-' . $months . '-' . $startDays;
        $sStartDate = date("Y-m-d", strtotime($sStartDate));
    } else {
        $sStartDate = $years . '-' . ($months) . '-' . $startDays;
        $sStartDate = date("Y-m-d", strtotime("+1 month", strtotime($sStartDate)));
    }

    $sEndDate = date("Y-m-d", strtotime("-1 month", strtotime($sEndDate)));

    // Start the variable off with the start date
    $aDays[] = $sStartDate;


    $sCurrentDate = $sStartDate;


    while ($sCurrentDate <= $sEndDate) {

        $sCurrentDate = date("Y-m-d", strtotime("+1 month", strtotime($sCurrentDate)));

        // Add this new day to the aDays array
        $aDays[] = $sCurrentDate;
    }

    // Once the loop has finished, return the
    // array of days.
    return $aDays;
}

function getDaysFromDateRange($weekDay, $startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $dates = array();
    while ($start <= $end) {
        $start->modify('+1 day');
        if (strtolower($start->format('l')) == strtolower($weekDay)) {
            $dates[] = $start->format('Y-m-d');
        }
    }
    return $dates;
}

/**
 * function change time to a given time zone
 *
 */
function calculateTimeByTimeZone($zone, $dateTime, $formate = 'Y-m-d H:i:s') {
    $date = new DateTime($dateTime, new DateTimeZone($zone));
    $serverTimeZone = date_default_timezone_get();
    $date->setTimezone(new DateTimeZone($serverTimeZone));
    return $date->format($formate);
}

function timezoneOffset($zone) {
    //$dateTime, $formate='Y-m-d H:i:s'
    //$utcdate = new DateTime(time(), new DateTimeZone('UTC'));
    $tzdate = new DateTime(time(), new DateTimeZone('UTC'));
    $tzdate->setTimezone(new DateTimeZone($zone));
    return $tzdate->getOffset();
}

function calculateSecondsFromUTC($zone) {
    $cdate = date('Y-m-d H:i:s');
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone($zone);
    $date = new DateTime($cdate, $UTC);
    $date->setTimezone($newTZ);
    $date->format('Y-m-d H:i:s');
    return $date->getOffset();
}

function getAllDataByTable($table, $attributes = array('id'), string $condationStr = null, array $condationArr = null, $limit = null, $orderColName = null) {
    $data = array();
    if (is_array($attributes)) {
        $attributesStr = implode(',', $attributes);
    } elseif (is_string($attributes)) {
        $attributesStr = $attributes;
    }

    $rest = Yii::app()->db->createCommand()
            ->select($attributesStr)
            ->from($table);

    if (!empty($condationStr) && !empty($condationArr))
        $rest->where($condationStr, $condationArr);

    if (!is_null($orderColName))
        $rest->order($orderColName);

    if ($limit != null && $limit == 1)
        $data = $rest->queryRow();
    else
        $data = $rest->queryAll();

    return $data;
}

function userActivity($user_id, $activity_id, $company_name, $activity_date, $activity_message, $activity_table) {
    $userActivity = new UserActivity();
    $userActivity->activity_id = $activity_id;
    $userActivity->user_id = $user_id;
    $userActivity->company_name = $company_name;
    $userActivity->activity_date = $activity_date;
    $userActivity->activity_message = $activity_message;
    $userActivity->activity_table = $activity_table;
    $userActivity->save(false);
}

///For graph section
function newsCount($startDate, $endDate) {
    $sql = "SELECT newsId FROM newsmaster WHERE  ((startdate  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( enddate  BETWEEN '$startDate'  AND '$endDate' ))";

    $data = Newsmaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

//pr($count);
function offertCount($startDate, $endDate) {
    $sql = "SELECT id FROM offers WHERE  ((created_at  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( modified_at  BETWEEN '$startDate'  AND '$endDate' ))";

    $data = Offers::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function workRequestCount($startDate, $endDate) {
    $sql = "SELECT id FROM workrequest WHERE  ((created_at  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( modified_at  BETWEEN '$startDate'  AND '$endDate' ))";

    $data = Workrequest::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function appUserCount($startDate, $endDate) {
    $sql = "SELECT companyId FROM companymaster WHERE member_type = 'App' AND ((created_at  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( modifiedDate  BETWEEN '$startDate'  AND '$endDate' ))";

    $data = Companymaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function eventCount($startDate, $endDate) {
    $sql = "SELECT eventid FROM eventmaster WHERE 
         (startdate  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( enddate  BETWEEN '$startDate'  AND '$endDate' )";
    $data = Eventmaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function memberCount($startDate, $endDate) {
    $sql = "SELECT companyId FROM companymaster WHERE 
        member_type = 'Web' AND ((created_at  BETWEEN '$startDate' AND  '$endDate' ) OR 
            ( modifiedDate  BETWEEN '$startDate'  AND '$endDate' ))";

    $data = Companymaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function totalNews() {
    $sql = "SELECT newsId FROM newsmaster WHERE YEAR(startdate) = YEAR(CURDATE()) AND
                MONTH(startdate) = MONTH(CURDATE()) GROUP BY newsId";
    $data = Newsmaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

//pr($count);
function totalOffer() {
    $sql = "SELECT id FROM offers WHERE YEAR(created_at) = YEAR(CURDATE()) AND
                MONTH(created_at) = MONTH(CURDATE()) GROUP BY id";

    $data = Offers::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function totalWorkRequest() {
    $sql = "SELECT id FROM workrequest WHERE YEAR(created_at) = YEAR(CURDATE()) AND
                MONTH(created_at) = MONTH(CURDATE()) GROUP BY id";

    $data = Workrequest::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function totalAppUser() {
    $sql = "SELECT companyId FROM companymaster WHERE member_type = 'App' AND (YEAR(created_at) = YEAR(CURDATE()) AND
                MONTH(created_at) = MONTH(CURDATE())) GROUP BY companyId";
    $data = Companymaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function totalEvent() {

    $sql = "SELECT eventid FROM eventmaster WHERE YEAR(startdate) = YEAR(CURDATE()) AND
                MONTH(startdate) = MONTH(CURDATE()) GROUP BY eventid";
    $data = Eventmaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function totalMember() {
    $sql = "SELECT companyId FROM companymaster WHERE member_type = 'Web' AND (YEAR(created_at) = YEAR(CURDATE()) AND
                MONTH(created_at) = MONTH(CURDATE())) GROUP BY companyId";
    $data = Companymaster::model()->findAllBySql($sql);
    $data = count($data);
    if (empty($data)) {
        $data = 0;
    }
    return $data;
}

function getAssociationId($post) {
    if (isset($post['ass_id']) && !empty($post['ass_id'])) {
        $assId = $post['ass_id'];
    } else {
        $session = Yii::app()->session;
        $assId = $session->get('associationId');
    }
    return $assId;
}

?>
